<?php
require_once("../lib/func.autoloader.php");
// lost_password.php
// SuperConstructor lost password utility
// Copyright 2007, Alex McClung
$sc = new SuperConstructor();

// Show the form by default
$sc->assign("showform", true);

// Was form data submitted?
if(count($_POST) > 0)
{
	// Try and find a user that matches the given username and e-mail address
	$user = new SC_User();
	
	// Load post data into local vars
	foreach($_POST as $varname => $value)
	{
		$$varname = $value;
		$user->$varname = $value;
		$sc->assign($varname, $value);
	}
	
	// Search the database. If we get exactly one record, send them an e-mail
	$search = new SimpleDBOSearch($user);
	$result = $search->Search();
	
	if($result->NumRows() == 1)
	{
		// Get the full record
		$user = $result->Next($user);
		
		// Generate a random password
		$gen = new PasswordGen();
		$password = $gen->GeneratePatternedPassword(rand(8,12));
		
		// Send them a mail
		$mail = $sc->GetMailer();
		$mail->From = "admin@yoursite.com"; // TODO: Replace this with the config variable
		$mail->AddAddress($user->email);
		$mail->Subject = "Lost Password";
		$mail->Body = "Hello {$user->name},\n\n\tYou have indicated that you have lost your password for {website}. Below is a temporary password that you can use to log-in.\n\n{$password}\n\nBe sure to change it the next time you log in.\n\nThanks,\n\t{admin name}";

		// Did it get sent OK?
		if(!$mail->Send())
		{
			MQ::Error("There seems to be a problem with the mail server. Please try again later.");
			MQ::Error("Mailer error: {$mail->ErrorInfo}");
		}
		else
		{
			MQ::OK("You have been sent a new password.");
			$sc->assign("showform", false);
		}
	}
	else
	{
		MQ::Error("The supplied information does not match any records in the database.");
	}
}

// Show the template
$sc->display("admin/pages/lost_password.tpl");
?>